#!/bin/bash
#The plotter is called from any CARBLogger driver
#It depends upon the installation of gnuplot and gnuplotfeed

while read line; do
eval $line
done < Config/config


cleanup()
{
    echo "Caught Signal ... cleaning up."
    if !(rm -f Data/.locked > /dev/null); then
        {
                  exit 1
        }
    fi
	my_interface=`ps -fe | grep interface | grep -v grep | awk '{ print $2 }'`  
   	feed_id="$$"
    for i in `pgrep ${feed_id} | grep -v ${my_interface}`
    do
    	kill -9 $i 2>/dev/null
    done 
    kill -9 ${feed_id}
    echo "Done cleanup ... quitting."
     exit 0
  }
                                                                                     

########################################################
#	GET THE PATH TO THE CURRENT DRIVER THE PARAMETERS TO PLOT                   #
########################################################
#DIR returns operating directory of the testd script

DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
#Plot dir Provides the CARBLogger Relative Directory
#PLOT_DIR=`echo ${DIR} | sed -s 's/\/home\/aqdms\/CARBLog//g'
#echo $PLOT_DIR
#########################################################
#	CHECK THE EXISTANCE OF NEEDED RESOURCES				#
#	MJV													#
#########################################################
if !( which feedgnuplot ); then
	{
	echo "No feedgnuplot has been found here"
	echo "exiting"
	exit 1
	}
elif !(which gnuplot); then
	{
 	echo "No gnuplot has been found here"
	echo "exiting"
	exit 1
	}
elif !( which pgrep ); then
	{
	echo "No pgrep...stopping"
	exit 1	
	}
fi
####################################################################################
#   SYNCHRONIZE 60 Sec PLOTTING CYCLE WITH FRONT DISPLAY ~ 5 sec after the top of the minute
#####################################################################################
while [ `date "+%S"` != 25 ]
do
    sleep .1
done
#CHECK FOR UNCONFIGURED DMS.CFG
#if [ ! -f sys_resources/.guid_provided ]
#then
#touch sys_resources/.guide_provided
#    xmessage 'CARBLogger uses the GNUPlot X11 terminal. Use g to toggle the grid,\
#     r for a ruler, zoom in with right clicking the mouse, p,u, and n to return\
#      to previous zoom states, a for autoscale '&
#fi
######################################################################
#	GRAB ALL OF THE DISPLAY PARAMETERS AND PLOT THEM
######################################################################
#TRAP CTRL+C
catchup=0
trap cleanup 1 2 3 6 15
while [ : ]; do
{
if [ $catchup -eq 0 ]; then
	{
		hour=`date '+%H'`
		minute=`date '+%M'`
		for h in `seq -w 0 $hour`
		do
			for m in `seq -w 0 59`
			do
				(grep "_${h}:${m}" | sed 's/--[A-Z]*--//' | sed 's/[_|:::T]/ /g' | awk '(/NOX=[-,0-9,.][-,0-9,.]* PPB/ || /NO2=[-,0-9,.][0-9,.]*/ || /NO=[-,0-9,.][0-9,.]* PPB/){ print }' | awk 'ORS=(FNR%3)?FS:RS { print }' | awk '{ print $3":"$4" "$19","$9","$29}' | sed 's/NOX=//g' | sed 's/NO2=//g' | sed 's/NO=//g' )<Data/${saroad}-`date '+%Y'`-`date '+%d'`-`date '+%m'`
			done
		done
	}
fi	
catchup=1
  
	#for i in NOX= ; 
	#do
			if [ `date '+%H:%M'` == "01:00" ]; then
			{
				echo clear
				sleep 60
			}
			else
			{

			tail -n 1000 Data/${saroad}-`date '+%Y'`-`date '+%d'`-`date '+%m'` | grep _`date '+%H:%M'` | sed 's/--[A-Z]*--//' | sed 's/[_|:::T]/ /g' | awk '(/NOX=[-,0-9,.][-,0-9,.]* PPB/ || /NO2=[-,0-9,.][0-9,.]*/ || /NO=[-,0-9,.][0-9,.]* PPB/){ print }' | awk 'ORS=(FNR%3)?FS:RS { print }' | awk '{ print $3":"$4" "$19","$9","$29}' | sed 's/NOX=//g' | sed 's/NO2=//g' | sed 's/NO=//g' 			
				#echo $no_data
				#no2_data=`echo ${data} | grep -o "NO2=[-,0-9,.][0-9,.]*" | sed -s 's/NO2=//g'` 
				#echo $no2_data
				#nox_data=`echo ${data} | grep -o "NOX=[-,0-9,.][-,0-9,.]*" | sed -s 's/NOX=//g'` 
				#echo $nox_data
				#data_string=`date "+%H:%M ${nox_data},${no2_data},${no_data}"`
				#echo $data_string
				#data=`echo ${data} | grep -o "${i}[-,0-9].[0-9,.]*" | sed -s 's/'${i}'//g' | awk '{ print "'`date "+%H:%M" `'" $0+0}'`
				#data2=`echo ${data} | grep -o "${i}[-,0-9].[0-9,.]*" | sed -s 's/'${i}'//g' | awk '{ print $0+0 }'`
				sleep 60
			}
			fi 
}
done 2>/dev/null | feedgnuplot --stream --domain --lines --xlabel 'Time [HH:MM]' --ylabel 'PPB' --y2label 'PPB' --timefmt '%H:%M' --extracmds 'set format x "%H:%M"; set terminal x11 noraise size 600,400 position 0,700' --points --curvestyle 0 'linewidth 2 linecolor rgb "red"' --legend 0 "Oxides of Nitrogen (left)" --curvestyle 1 'linewidth 2 linecolor rgb "blue"' --legend 1 "NO2 (left)" --curvestyle 2 'linewidth 2 linecolor rgb "black"' --legend 2 "NO (right)" --y2 2 --title "Oxides of Nitrogen"



